<template>
  <div class="excel-box">
    <el-button :type="type ? type : 'info'" :plain="plain" :icon="icon" :size="size" :disabled="disabled" @click="handleShow()">{{ name }}</el-button>
    <!-- dialogShow start -->
    <el-dialog
      class="dialog-template-export"
      width="74%"
      append-to-body
      top="4vh"
      :title="name"
      :close-on-click-modal="false"
      :visible.sync="dialogShow">
      <div class="dialog-template-export-content">
        <div class="zone-content-box">
          <el-checkbox class="zone-content-box-head" v-model="checkedAll" :indeterminate="isIndeterminate" @change="checkedAllItem">全选</el-checkbox>
          <div class="body-item" v-for="(el, elIndex) of groupColumnList" :key="elIndex">
            <div class="body-item-total">
              <el-checkbox :indeterminate="el.isIndeterminate" v-model="el.checked" @change="setChildrenChecked(el,elIndex)">{{ el.groupName }}</el-checkbox>
            </div>
            <div class="body-item-content">
              <el-checkbox-group v-model="el.checkedCities" @change="checkedMenuChange(elIndex)">
                <el-checkbox v-for="els of el.columnList" :label="els.columnName" :key="els.columnName">{{ els.columnDesc }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="zone-content-radio">
          <span class="zone-content-radio-title">我的模板</span>
          <el-radio-group v-model="activeTemplateId" v-if="templateList.length">
            <el-radio v-for="(item, index) in templateList" :key="`template-${index}`" :label="item.id" @click.native.prevent="handleTemplate(item.id,item.templateName)">
              <span class="zone-content-radio-templateName">{{ item.templateName }}</span>
              <span class="zone-content-radio-number">{{ item.columnList.length }}</span>
              <div class="zone-content-radio-button">
                <el-button type="text" @click="handleSubmit('edit',undefined,item.id)">保 存</el-button>
                <el-button type="text" @click="handleDelete(item.id)">删 除</el-button>
                <el-button type="text" @click="handleName('edit',item.templateName,item.id)">修改名称</el-button>
              </div>
            </el-radio>
          </el-radio-group>
          <div class="f-12" v-else>
              暂无模板
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="handleName('add')" :loading="dialogLoading">保存为模板</el-button>
        <el-button type="primary" @click="handleExport()" :loading="dialogLoading">导出选中字段数据</el-button>
      </div>
    </el-dialog>
    <!-- dialogShow end -->
    <!-- dialogName start -->
    <el-dialog title="模板名称" class="dialog-name" width="480px" append-to-body :close-on-click-modal="false" :visible.sync="dialogName">
      <el-form ref="nameForm" class="name-form mt20" label-width="78px"
        :model="nameForm">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model.trim="nameForm.templateName" placeholder="请输入模板名称" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogName = false">取 消</el-button>
        <el-button type="primary" :loading="dialogLoading"
          @click="handleSubmit('name', nameForm.templateName)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- dialogName end -->
  </div>
</template>

<script>
import request from '@/utils/request';
import * as API_Export_Template from './api';

export default {
  name: 'DgTemplateExport',
  // {name: 按钮名; type: 按钮类型; size: 尺寸; disabled: 禁用; url: 导入地址}
  // url必传
  props: {
    name: {
      type: String,
      default: '导出'
    },
    type: String,
    size: String,
    plain: {
      type: Boolean,
      default: false
    },
    disabled: Boolean,
    code: String,
    url: String,
    needParams: {
      type: Boolean,
      default: false
    },
    icon: {
      type: String,
      default: 'el-icon-download'
    },
    exportIds: Array
  },
  // props: ['name', 'type', 'size', 'disabled', 'url'],
  data() {
    return {
      dialogShow: false,
      dialogLoading: false,
      configId: undefined,
      // 模板列表
      templateList: [],
      activeTemplateId: undefined,
      activeTemplateName: undefined,
      // 已选字段
      checkOptions: {
        animation: 150,
        group: { name: 'selectGroup', put: true },
        sort: true,
        handle: '.select-cell'
      },
      selectColumnList: [],
      // 导出字段
      columnList: [],
      groupColumnList: [],
      // 模板名称
      dialogName: false,
      dialogType: 'add',
      nameForm: {
        templateName: undefined
      },
      // 全选按钮
      isIndeterminate: false,
      checkedAll: false
    };
  },
  methods: {
    // 处理数据
    hanldeColumnList(columnList){
      let isIndeterminate = false;
      this.groupColumnList.forEach(item => {
        columnList.forEach((el) => {
          if (item.groupName == el.groupName) {
            item.checkedCities.push(el.columnName);
          }
        });
        item.isIndeterminate = item.checkedCities.length > 0 && item.checkedCities.length < item.columnList.length;
        item.checked = item.checkedCities.length === item.columnList.length;
        if (item.isIndeterminate) { isIndeterminate = true; }
      });
      // 判断全选多选框状态
      this.allCheckedChange(isIndeterminate);
    },
    // 获取选中的导出字段
    getSelectedList(){
      this.selectColumnList = [];
      this.groupColumnList.forEach(item => {
        item.columnList.forEach(el => {
          if (item.checkedCities.indexOf(el.columnName) != -1) {
            this.selectColumnList.push(el);
          }
        });
      });
    },
    // 全选
    checkedAllItem(val){
      this.groupColumnList.forEach((item,index) => {
        item.checked = val;
        if (val) {
          this.setChildrenChecked({ checked: true },index);
        } else {
          this.setChildrenChecked({ checked: false },index);
        }
      });
    },
    // 一级菜单
    setChildrenChecked(_node,index) {
      this.groupColumnList[index].isIndeterminate = false;
      if (!_node.checked) {
        // 不选中
        this.groupColumnList[index].checkedCities = [];
      } else {
        // 选中
        this.groupColumnList[index].checkedCities =  this.groupColumnList[index].columnList.map((item) => { return item.columnName; });
      }
      // 判断全选多选框状态
      this.allCheckedChange(this.groupColumnList[index].isIndeterminate);
    },
    // 多选框change事件
    checkedMenuChange(index) {
      let groupColumnList =  this.MixinClone(this.groupColumnList);
      groupColumnList[index].isIndeterminate = groupColumnList[index].checkedCities.length > 0 && groupColumnList[index].checkedCities.length < groupColumnList[index].columnList.length;
      groupColumnList[index].checked = groupColumnList[index].checkedCities.length === groupColumnList[index].columnList.length;
      this.groupColumnList =  groupColumnList;
      // 判断全选多选框状态
      this.allCheckedChange(this.groupColumnList[index].isIndeterminate);
    },
    // 判断全选多选框的状态
    allCheckedChange(isIndeterminate){
      let allData =  this.groupColumnList.filter(item => {
        return item.checked == true;
      });
      this.isIndeterminate = (allData.length > 0 && allData.length < this.groupColumnList.length)||isIndeterminate;
      this.checkedAll = allData.length === this.groupColumnList.length;
    },
    /**
      * @date 2024/05/14
      * @author wolfMan
      * @description {显示导出模板弹层}
    */
    handleShow () {
      this.activeTemplateId = undefined;
      this.activeTemplateName = undefined;
      this.clearSelect();
      let _params1 = {
        moduleCode: this.code
      };
      API_Export_Template.getTemplateColumnList(_params1).then(response => {
        if (response.success) {
          this.getTemplateData();
          this.dialogShow = true;
          const { id,groupColumnList } = response.data || {};
          this.configId = id;
          this.$nextTick(() => {
            this.handleTreeData(groupColumnList);
            this.groupColumnList = groupColumnList;
          });
        } else {
          this.$modal.msgError(response.msg);
        };
      });
    },
    // 获取模板列表
    getTemplateData(){
      let _params2 ={
        body: {
          moduleCode: this.code
        },
        pageNum: 1,
        pageSize: 9999
      };
      API_Export_Template.getTemplateList(_params2).then(response => {
        if (response.success) {
          let { records } = response.data || {};
          this.$nextTick(() => {
            this.templateList = records || [];
          });
        } else {
          this.$modal.msgError(response.msg);
        };
      });
    },
    // 处理树形数据
    handleTreeData(groupColumnList){
      groupColumnList.forEach(item => {
        this.$set(item,'checked',false);
        this.$set(item,'checkedCities',[]);
      });
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {清空选中字段}
    */
    clearSelect () {
      this.isIndeterminate = false;
      this.checkedAll = false;
      let _groupColumnList = this.groupColumnList.map(item => {
        item.checked= false;
        item.isIndeterminate = false;
        item.checkedCities= [];
        return item;
      });
      this.selectColumnList = [];
      this.groupColumnList = _groupColumnList;
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {模板选中/取消}
    */
    handleTemplate (_id,_name) {
      if (this.activeTemplateId === _id) {
        this.activeTemplateId = undefined;
        this.activeTemplateName = undefined;
        // 清空选中字段
        this.clearSelect();
      } else {
        this.dialogLoading = true;
        // 选中赋值
        this.activeTemplateId = _id;
        this.activeTemplateName = _name;
        // 查询模板详情
        API_Export_Template.getTemplateDetail({ id: _id }).then(response => {
          if (response.success) {
            this.clearSelect();
            const { columnList } = response.data || {};
            if (columnList.length) {
              this.hanldeColumnList(columnList);
            }
          } else {
            this.$modal.msgError(response.msg);
          };
        }).always(() => {
          this.dialogLoading = false;
        });
      };
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {删除模板}
    */
    handleDelete (_id) {
      this.dialogLoading = true;
      API_Export_Template.deleteExportTemplate({ ids: [_id] }).then(response => {
        if (response.success) {
          this.$modal.msgSuccess('模板删除成功');
          // 清空选中数据
          this.clearSelect();
          // 去除选中项目
          this.$nextTick(() => {
            this.activeTemplateId = undefined;
            this.activeTemplateName = undefined;
            this.getTemplateData();
          });
        } else {
          this.$modal.msgError(response.msg);
        };
      }).always(() => {
        this.dialogLoading = false;
      });
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {显示模板名弹层}
    */
    handleName (_type, _name, _id) {
      console.log(_id);
      this.nameForm.templateName = undefined;
      this.dialogName = true;
      this.dialogType = _type;
      if (_type === 'edit') {
        this.nameForm.templateName = _name;
        if (this.activeTemplateId) { this.activeTemplateId = undefined; }
      };
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {模板保存}
    */
    handleSubmit (_type, _name, _id) {
      this.getSelectedList();
      if (_type === 'name' && !_name && _name !== 0) {
        this.$modal.msgError('请输入模板名称');
        return;
      };
      this.dialogLoading = true;
      let _params = {
        configId: this.configId,
        moduleCode: this.code
      };
      // 默认修改模板接口
      let _service = API_Export_Template.editExportTemplate;
      // 保存模板名称弹层进入, 否则是直接修改模板
      if (_type === 'name') {
        _params.templateName = _name;
      } else {
        _params.templateName = this.activeTemplateName;
        _params.columnList = this.selectColumnList;
      };
      // 未选中模板，说明是新增模板接口; 否则说明是修改
      if (this.dialogType == 'add' && _type!='edit') {
        _service = API_Export_Template.addExportTemplate;
        _params.columnList = this.selectColumnList;
      } else {
        _params.id = _id?_id:this.activeTemplateId;
      };
      _service(_params).then(response => {
        if (response.success) {
          this.$modal.msgSuccess('模板保存成功');
          this.getTemplateData();
          this.dialogName = false;
        } else {
          this.$modal.msgError(response.msg);
        };
      }).always(() => {
        this.dialogLoading = false;
      });
    },
    /**
      * @date 2024/05/15
      * @author wolfMan
      * @description {导出}
    */
    handleExport () {
      this.dialogLoading = true;
      this.getSelectedList();
      let _params = {
        fieldNameList: this.selectColumnList.map(item => {
          return item.columnName;
        })
      };
      if (this.activeTemplateId || this.activeTemplateId === 0) {
        _params.templateId = this.activeTemplateId;
      };
      if (this.needParams) {
        this.$emit('getParams', pageParams => {
          if (this.exportIds.length > 0) {
            _params = {
              ..._params,
              body: {
                ids: this.exportIds
              }
            };
          } else if (pageParams.paramsOnly) {
            _params = {
              ..._params,
              ...pageParams
            };
          } else {
            for (const _key in pageParams) {
              if (pageParams[_key] === '') { // 当条件值为''时去除条件
                delete pageParams[_key];
              }
            };
            _params = {
              ..._params,
              pageNum: 1,
              pageSize: 99999,
              body: pageParams || {}
            };
          };
        });
      };
      request({
        url: this.url,
        method: 'post',
        data: _params,
        timeout: this.timeout || 60000
      }).then(response => {
        if (response && response.success) {
          this.dialogShow = false;
          let _useData = response.data;
          if (_useData.syncDownload) {
            this.$confirm(`已为您筛选出${response.data.count}条数据，确认导出吗？`, '提示', {
              confirmButtonText: '下载',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              window.open(response.data.fileUrl);
            }).catch(() => {
              console.log('取消');
            });
          } else {
            this.$confirm(response.msg, '提示', {
              confirmButtonText: '立即查看',
              cancelButtonText: '取消',
              type: 'success'
            }).then(() => {
              this.$router.replace({ path: '/export-list' });
            }).catch(() => {
              console.log('取消');
            });
          };
        } else {
          this.$modal.msgError(response.msg);
        };
      }).always(() => {
        this.dialogLoading = false;
      });
    }
  }
};
</script>

<style type="text/scss" lang="scss">
.dialog-template-export {
  .el-dialog__body {
    padding: 0px;
  }
  .title-name {
    padding-bottom: 5px;
    line-height: 20px;
    color: #515a6e;
    font-size: 14px;
    font-weight: 600;
  }
  .flex-row-box {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -3px;
    padding: 0 3px 12px 0;
    min-height: 32px;
    .cell-name {
      display: block;
      padding: 0 2px;
      margin: 6px 3px 0 3px;
      width: 92px;
      height: 32px;
      line-height: 32px;
      border-radius: 2px;
      box-sizing: border-box;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      text-align: center;
      cursor: pointer;
      background: #1677FF;
      color: #fff;
      font-size: 12px;
      &.active {
        background: #D0D0D0;
        color: #636363;
      }
      &.unselect {
        background: #F6F6F6;
        color: #1677FF;
      }
      &.sortable-chosen {
        border: solid 1px #1677FF;
        background: #fff;
        color: #1677FF;
      }
    }
  }
  &-content{
    display: flex;
    .zone-content{
      &-box{
        width: calc(100% - 400px);
        padding:16px;
        border-right: 1px solid #dddfe2;
        &-head{
          padding: 2px;
        }
        .body-item{
          display: flex;
          background-color: #f5f6f9;
          border:1px solid#dddfe2;
          align-items: center;
          &-total{
            width: 136px;
            height: 100%;
            padding: 0px 16px;
            flex-shrink: 0;
          }
          &-content{
            min-height: 40px;
            padding: 16px 16px 0px 16px;
            border-left: 1px solid #dddfe2;
            .el-checkbox{
              width: 180px;
              margin-bottom: 12px;
              margin-right: 0px;
            }
            &-empty{
              color: #afafaf;
              line-height: 24px;
            }
          }
        }
        :not(:first-child).body-item{
          border-top: none;
        }
      }
      &-radio{
        min-width: 346px;
        padding: 16px;
        &-title{
          font-size: 17px;
          margin-bottom: 20px;
          display: inline-block;
        }
        &-templateName{
          display: inline-block;
          width: 150px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          -o-text-overflow: ellipsis;
        }
        &-number{
          position: absolute;
          left: 176px;
          line-height: 15px;
        }
        &-button{
          position: absolute;
          top: -6px;
          left: 220px;
        }
        .f-12{
          color: #afafaf;
          text-align: center;
        }
        .el-radio-group{
          width: 100%;
          .el-radio{
            position: relative;
            display: block;
            margin-right: 0px;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
}
.export-button{
padding:7px 15px;
}
</style>